package com.imooc.mall.model.service.impl;

import com.imooc.mall.model.dao.UserMapper;
import com.imooc.mall.model.exception.ImoocMallException;
import com.imooc.mall.model.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.model.service.UserService;
import com.imooc.mall.model.util.MD5Util;
import org.apache.catalina.mapper.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;


    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }

    @Override
    public void register(String userName,String password) throws ImoocMallException {
        //查询用户是否存在，不予许重名
        User result = userMapper.selectByName(userName);
        if(result!=null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NEED_EXITSTED);
        }
        User user=new User();
        user.setUsername(userName);
        try {
            user.setPassword(MD5Util.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int i = userMapper.insertSelective(user);
        if(i==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String userName, String password) throws ImoocMallException {
        String md5str=null;
        try {

            md5str=MD5Util.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userMapper.selectLogin(userName, md5str);
        if(user==null){
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_PASSWORD);
        }
        return user;
    }
    @Override
    public void updateInformation(User user) throws ImoocMallException {
        //更新个性签名
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount>1){
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean checkAdminRole(User user){
        //为1是普通用户，2是管理员
        return user.getRole().equals(2);
    }
}
